package com.yanqu.road.handle;

import com.yanqu.road.NettyMgr;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.yanqu.road.connect.AgentServerConnectionGroup;
import com.yanqu.road.message.YanQuMessage;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class AgentServerHandler extends SimpleChannelInboundHandler<YanQuMessage> {

    private static Logger logger = LogManager.getLogger(AgentServerHandler.class.getName());

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, YanQuMessage yanQuMessage) throws Exception {
        AgentMsgHandle.handleMsg(ctx, yanQuMessage);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        AgentConnectionCloseHandle.handle(ctx);
        logger.info("channel 断开 : {}" , ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        AgentServerConnectionGroup connectionGroup = (AgentServerConnectionGroup) ctx.channel().attr(NettyMgr.LINKED_CLIENT).get();
        if (null != connectionGroup) {
            logger.error("msg : {}", connectionGroup.toString(), cause);
        }
        ctx.close();
        logger.error("channel 异常 : {} 错误信息 : " , ctx.channel().remoteAddress() , cause);
    }

}
